import { Ref, ref } from 'vue';
import { showToast  , showLoadingToast ,closeToast} from 'vant';

// 第一个接收是泛型接口返回字段 , 第二个是传给接口的字段

type TApiFun<TData, TParams = any > = (params: TParams) => Promise<TData>;

interface AutoRequestOptions {
   // 定义一下初始状态
  loading?: boolean;
  // 接口调用成功时的回调
  onSuccess?: (data: any) => void;
}

type AutoRequestResult<TData, TParams = any> = [Ref<boolean>, TApiFun<TData, TParams>];

/* 控制loading状态的自动切换hook */
export   function useAutoRequest<TData, TParams = any>(fun: TApiFun<TData, TParams>, options?: AutoRequestOptions): AutoRequestResult<TData, TParams> {
  const { loading = false, onSuccess } = options || { loading: false };

  const requestLoading = ref(loading);
  
  const run: TApiFun<TData, TParams> = (params) => {
    requestLoading.value = true;
    showLoadingToast({
      message: 'Loading...',
      forbidClick: true,
      duration: 0,
    });
    return new Promise((resolve, reject)=> {
       fun({
        ...params
       })
      .then((res) => {
        onSuccess && onSuccess(res);
        resolve(res)
        return res;
      })
      .finally(() => {
        
        requestLoading.value = false;
      })
      .catch(err =>{
        reject()
      })
    })
  };

  return [requestLoading, run];
}